package com.wannengbang.cloudleader.utils;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentCallbacks;
import android.content.res.Configuration;
import android.util.DisplayMetrics;

/**
 * {
 * switch (unit) {
 * case COMPLEX_UNIT_PX:
 * return value;
 * case COMPLEX_UNIT_DIP:
 * return value * metrics.density;
 * case COMPLEX_UNIT_SP:
 * return value * metrics.scaledDensity;
 * case COMPLEX_UNIT_PT:
 * return value * metrics.xdpi * (1.0f/72);
 * case COMPLEX_UNIT_IN:
 * return value * metrics.xdpi;
 * case COMPLEX_UNIT_MM:
 * return value * metrics.xdpi * (1.0f/25.4f);
 * }
 * <p>核心原理 <p>
 * density=当前设备屏幕总宽度（单位为px）/ 设计图总宽度（单位为 dp)，
 * 为什么要算出density。在安卓源码TypedValue类中可以看到这段代码，我们通常用此方法进行dp和px的转化。density 的意思就是 1 dp 占当前设备多少像素，
 * 我们知道density 在每个设备上都是固定的。因此可以得出DPI / 160 = density，而屏幕的总 px 宽度 / density = 屏幕的总 dp 宽度，最终 dp=(px/dpi)*160
 */

public class UIAdapterUtils {


    // 系统的Density
    private static float sNoncompatDensity;
    // 系统的ScaledDensity
    private static float sNoncompatScaledDensity;

    public static void setCustomDensity(Activity activity, final Application application) {
        DisplayMetrics displayMetrics = application.getResources().getDisplayMetrics();
        if (sNoncompatDensity == 0) {
            sNoncompatDensity = displayMetrics.density;
            sNoncompatScaledDensity = displayMetrics.scaledDensity;
            // 监听在系统设置中切换字体
            application.registerComponentCallbacks(new ComponentCallbacks() {
                @Override
                public void onConfigurationChanged(Configuration newConfig) {
                    if (newConfig != null && newConfig.fontScale > 0) {
                        sNoncompatScaledDensity = application.getResources().getDisplayMetrics().scaledDensity;
                    }
                }

                @Override
                public void onLowMemory() {

                }
            });
        }
        // 此处以360dp的设计图作为例子
        float targetDensity = displayMetrics.widthPixels * 1f / 375f;
        float targetScaledDensity = targetDensity * (sNoncompatScaledDensity / sNoncompatDensity);
        int targetDensityDpi = (int) (160 * targetDensity);
        displayMetrics.density = targetDensity;
        displayMetrics.scaledDensity = targetScaledDensity;
        displayMetrics.densityDpi = targetDensityDpi;

        DisplayMetrics activityDisplayMetrics = activity.getResources().getDisplayMetrics();
        activityDisplayMetrics.density = targetDensity;
        activityDisplayMetrics.scaledDensity = targetScaledDensity;
        activityDisplayMetrics.densityDpi = targetDensityDpi;
    }


}
